//
//  HomeWorkDetailViewController.m
//  ZPIOSEducation
//
//  Created by 董伟1 on 17/1/11.
//  Copyright © 2017年 mini1. All rights reserved.
//

#import "HomeWorkDetailViewController.h"
#import "HomeWorkContentCell.h"
#import "StartWriteHomeworkCell.h"

@interface HomeWorkDetailViewController () <UITableViewDelegate,UITableViewDataSource,UINavigationControllerDelegate,UIImagePickerControllerDelegate,WriteHomeWorkCellDelegate>
{
    UIButton  *rightBtn;
    NSMutableArray  *dataArray;
    
    BOOL  editing;
    
    UITextView  *textView;
    NSMutableArray  *picArray;
}

@property (weak, nonatomic) IBOutlet UITableView *mainTableView;
@property (weak, nonatomic) IBOutlet UIView *bottomView;
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *tableViewBottom;

@end

@implementation HomeWorkDetailViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    NSInteger  type = [self.typeStr  integerValue];
    //type  1写作业  2待评分  3已评分
    self.bottomView.hidden = YES;
    self.tableViewBottom.constant = 0.;
    if (type == 1) {
        self.title = @"写作业";
        self.navigationItem.rightBarButtonItem = [[UIBarButtonItem  alloc] initWithTitle:@"交作业" style:UIBarButtonItemStylePlain target:self action:@selector(commitHomeWorkButtonClick)];
        self.bottomView.hidden = NO;
        self.tableViewBottom.constant = 49.;
        editing = YES;
    }else if (type == 2) {
        //待评分
        self.title = @"作业详情";
        rightBtn = [UIButton  buttonWithType:UIButtonTypeCustom];
        rightBtn.frame = CGRectMake(0, 12, 40, 30);
        rightBtn.titleLabel.font = [UIFont systemFontOfSize:14.];
        [rightBtn setTitle:@"修改" forState:UIControlStateNormal];
        [rightBtn setTitle:@"完成" forState:UIControlStateSelected];
        [rightBtn  setTitleColor:[UIColor  whiteColor] forState:UIControlStateNormal];
        [rightBtn  addTarget:self action:@selector(navRightButtoClick:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *barItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
        self.navigationItem.rightBarButtonItem = barItem;
        self.bottomView.hidden = YES;
        self.tableViewBottom.constant = 0.;
        editing = NO;
    }else {
        //已评分
        self.title = @"作业详情";
        self.bottomView.hidden = YES;
        self.tableViewBottom.constant = 0.;
        editing = NO;
    }
    
    self.mainTableView.delegate = self;
    self.mainTableView.dataSource = self;

    dataArray = [[NSMutableArray  alloc] init];
    picArray = [[NSMutableArray  alloc] init];
    
    [self  requestData];
    
}

- (void)commitHomeWorkButtonClick
{
    if (textView.text.length == 0 && picArray.count == 0) {
        [ZPPromptView  showMessage:@"请先完成作业哦"];
        return;
    }
    [self  upLoadLocalImage];
}

- (void)navRightButtoClick:(id)sender
{
    if (editing) {
        if (textView.text.length == 0 && picArray.count == 0) {
            [ZPPromptView  showMessage:@"请先完成作业哦"];
            return;
        }
        [self  upLoadLocalImage];
        
    }else {
        UIButton  *tempBtn = (UIButton  *)sender;
        tempBtn.selected = !tempBtn.selected;
        if (tempBtn.selected) {
            self.bottomView.hidden = NO;
            self.tableViewBottom.constant = 49.;
        }else {
            self.bottomView.hidden = YES;
            self.tableViewBottom.constant = 0.;
        }
        editing = tempBtn.selected;
        [self.mainTableView  reloadData];
        
    }
}

- (IBAction)photoButtonClick:(id)sender
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary]) {
        if (picArray.count > 5) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"最多只能上传6张图片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

- (IBAction)cameraButtonClick:(id)sender
{
    if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]) {
        if (picArray.count > 5) {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"最多只能上传6张图片" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
            [alert show];
            return;
        }
        UIImagePickerController * picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        picker.allowsEditing = YES;
        picker.sourceType = UIImagePickerControllerSourceTypeCamera;
        [self presentViewController:picker animated:YES completion:nil];
    }
}

#pragma mark - 网络相关
#pragma mark 获取详情数据
- (void)requestData
{
    [self  showHudithString:@"加载中..."];
    NSDictionary  *paramDic = [NSDictionary  dictionaryWithObjectsAndKeys:[NSString  stringWithFormat:@"%@",self.idStr],@"id",[NSString  stringWithFormat:@"%@",self.typeStr],@"type", nil];
    [[ZPNetworking  sharedZPNetworking] POST:APIHome@"home/getHomeworkContent.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            UIView  *headerView = [[[NSBundle mainBundle] loadNibNamed:@"HomeWorkDetailHeaderView" owner:self options:nil] lastObject];
            headerView.frame = CGRectMake(0, 0, SCREENWIDTH, 54);
            UILabel  *titleLab = (UILabel  *)[headerView  viewWithTag:100];
            titleLab.text = [NSString  stringWithFormat:@"%@",[[responseObject  objectForKey:@"result"] objectForKey:@"dates"]];
            UILabel  *classLab = (UILabel  *)[headerView  viewWithTag:101];
            classLab.text = [NSString  stringWithFormat:@"%@",[[responseObject  objectForKey:@"result"] objectForKey:@"name"]];
            
            UILabel  *typeLabel = (UILabel  *)[headerView  viewWithTag:102];
            typeLabel.hidden = YES;
            UIView  *scoreView = (UIView  *)[headerView  viewWithTag:103];
            scoreView.hidden = YES;
            NSInteger  type = [self.typeStr  integerValue];
            if (type == 2) {
                typeLabel.hidden = NO;
                typeLabel.layer.cornerRadius = 9.5;
                typeLabel.layer.masksToBounds = YES;
            }else if (type == 3) {
                scoreView.hidden = NO;
                scoreView.layer.cornerRadius = 25.;
                scoreView.layer.borderWidth = 2.;
                scoreView.layer.borderColor = RGBACOLOR(255, 86, 86, 1.).CGColor;
                scoreView.layer.masksToBounds = YES;
                
                UILabel  *scoreLab = (UILabel  *)[scoreView  viewWithTag:200];
                scoreLab.text = [NSString  stringWithFormat:@"%@分",[[[responseObject  objectForKey:@"result"] objectForKey:@"teacherHomework"] objectForKey:@"score"]];
                headerView.frame = CGRectMake(0, 0, SCREENWIDTH, 78);
            }
            self.mainTableView.tableHeaderView = headerView;
            
            
            [dataArray  removeAllObjects];
            NSDictionary  *teacherAssess = [[responseObject  objectForKey:@"result"] objectForKey:@"teacherAssess"];
            if ([teacherAssess  isKindOfClass:[NSDictionary  class]] && teacherAssess.count > 0) {
                NSDictionary  *tempDic = [NSDictionary  dictionaryWithObjectsAndKeys:@"1",@"type",teacherAssess,@"data", nil];
                [dataArray  addObject:tempDic];
            }
            
            NSDictionary  *teacherHomework = [[responseObject  objectForKey:@"result"] objectForKey:@"teacherHomework"];
            if ([teacherHomework  isKindOfClass:[NSDictionary  class]] && teacherHomework.count > 0) {
                NSDictionary  *tempDic = [NSDictionary  dictionaryWithObjectsAndKeys:@"2",@"type",teacherHomework,@"data", nil];
                [dataArray  addObject:tempDic];
            }
            
            [picArray  removeAllObjects];
            if (type == 1) {
                NSDictionary  *tempDic = [NSDictionary  dictionaryWithObjectsAndKeys:@"3",@"type",[NSDictionary  dictionaryWithObjectsAndKeys:@"",@"content",picArray,@"picture", nil],@"data", nil];
                [dataArray  addObject:tempDic];
            }else {
                NSDictionary  *stuHomework = [[responseObject  objectForKey:@"result"] objectForKey:@"stuHomework"];
                if ([stuHomework  isKindOfClass:[NSDictionary  class]] && stuHomework.count > 0) {
                    NSArray  *picture = [stuHomework  objectForKey:@"picture"];
                    NSInteger  count = [picture  count];
                    for (int i = 0; i < count; i ++) {
                        NSDictionary  *picDic = [NSDictionary  dictionaryWithObjectsAndKeys:[picture objectAtIndex:i],@"data",@"1",@"type", nil];
                        [picArray  addObject:picDic];
                    }
                    
                    NSDictionary  *tempDic = [NSDictionary  dictionaryWithObjectsAndKeys:@"3",@"type",[NSDictionary  dictionaryWithObjectsAndKeys:[stuHomework  objectForKey:@"content"],@"content",picArray,@"picture", nil],@"data", nil];
                    [dataArray  addObject:tempDic];
                }
            }
            
            [self.mainTableView  reloadData];
        }
        
    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark 上传图片
- (void)upLoadLocalImage
{
    [self  showHudithString:@"加载中..."];
    NSMutableArray  *localImgArr = [[NSMutableArray  alloc] init];
    NSMutableArray  *networkImgArr = [[NSMutableArray  alloc] init];
    NSInteger  picCount = [picArray  count];
    for (int i = 0; i < picCount; i ++) {
        NSDictionary  *tempDic = [picArray  objectAtIndex:i];
        NSInteger  type = [[tempDic  objectForKey:@"type"] integerValue];
        if (type == 1) {
            [networkImgArr  addObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"data"]]];
        }else if (type == 2) {
            [localImgArr  addObject:tempDic];
        }
    }
    
    AFHTTPSessionManager  *manger = [AFHTTPSessionManager  manager];
    if (localImgArr.count == 0) {
        [self  commitHomeWorkWithArray:networkImgArr];
    }else {
        [manger  POST:APIUC@"image/addImage.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
            NSInteger  localImgCount = [localImgArr  count];
            for (int i = 0; i < localImgCount; i ++) {
                NSDictionary  *tempDic = [localImgArr objectAtIndex:i];
                [formData  appendPartWithFileData:[tempDic  objectForKey:@"data"] name:@"images" fileName:[tempDic  objectForKey:@"name"] mimeType:@"image/jpeg"];
            }
        } progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSLog(@"=======%@",responseObject);
            if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
                if ([[[responseObject  objectForKey:@"result"] objectForKey:@"result"] isKindOfClass:[NSArray  class]]) {
                    NSArray  *result = [[responseObject  objectForKey:@"result"] objectForKey:@"result"];
                    NSInteger  resultCount = [result  count];
                    for (int i = 0; i < resultCount; i ++) {
                        NSDictionary  *tempDic = [result  objectAtIndex:i];
                        [networkImgArr  addObject:[NSString  stringWithFormat:@"%@",[tempDic  objectForKey:@"value"]]];
                    }
                }
                [self  commitHomeWorkWithArray:networkImgArr];
                
            }else {
                [self  hiddenHud];
            }
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            [self  hiddenHud];
        }];
    }
    
}

#pragma mark 提交作业
- (void)commitHomeWorkWithArray:(NSMutableArray  *)array
{
    NSMutableDictionary  *paramDic = [NSMutableDictionary  dictionaryWithObjectsAndKeys:
                                      [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"memberId"],@"memberId",
                                      [[ZPAuthStore  sharedZPAuthStore].userToDic  objectForKey:@"stuId"],@"studentId",
                                      [NSString  stringWithFormat:@"%@",self.typeStr],@"buttonType",
                                      nil];
    if (textView.text.length > 0) {
        [paramDic  setObject:textView.text forKey:@"homeworkAnswer"];
    }
    if ([self.typeStr integerValue] == 1) {
        [paramDic  setObject:[NSString  stringWithFormat:@"%@",self.idStr] forKey:@"homeworkId"];
    }else {
        [paramDic  setObject:[NSString  stringWithFormat:@"%@",self.idStr] forKey:@"id"];
    }
    if (array.count > 0) {
        NSString  *imgUrlStr = [NSString  stringWithFormat:@"%@",[array  componentsJoinedByString:@","]];
        [paramDic  setObject:imgUrlStr forKey:@"imgUrl"];
    }
    [[ZPNetworking  sharedZPNetworking] POST:APIHome@"home/processHomework.json" parameters:paramDic progress:^(NSProgress * _Nullable progress) {
        
    } success:^(id  _Nonnull responseObject) {
        NSLog(@"======%@",responseObject);
        [self  hiddenHud];
        if ([[responseObject  objectForKey:@"code"] integerValue] == 200) {
            if ([[[responseObject  objectForKey:@"result"] objectForKey:@"isOk"] boolValue]) {
                NSInteger  type = [self.typeStr  integerValue];
                if (type == 1) {
                    [ZPPromptView  showMessage:@"提交作业成功"];
                }else if (type == 2) {
                    [ZPPromptView  showMessage:@"修改作业成功"];
                }
                [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshHomeWorkList" object:nil];
                [[NSNotificationCenter  defaultCenter] postNotificationName:@"refreshCourseList" object:nil];
                [self.navigationController  popViewControllerAnimated:YES];
            }
        }else {
            [ZPPromptView  showMessage:[responseObject  objectForKey:@"codeMsg"]];
        }

    } failure:^(NSError * _Nonnull error) {
        [self  hiddenHud];
    }];
}

#pragma mark - UITableView Delegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [dataArray  count];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSDictionary  *tempDic = [dataArray  objectAtIndex:indexPath.row];
    NSInteger  type = [[tempDic  objectForKey:@"type"] integerValue];
    NSInteger  pictureCount = [[[tempDic  objectForKey:@"data"] objectForKey:@"picture"] count];
    CGFloat  picHeight = 0.;
    if (pictureCount > 0) {
        if (pictureCount % 3 == 0) {
            picHeight = 87 * (pictureCount / 3);
        }else {
            picHeight = 87 * ((pictureCount / 3) + 1);
        }
    }
    //type: 1老师评语  2作业内容  3我的答案
    if (type == 3 && editing) {
        return 154 + picHeight;
    }else {
        NSString  *content = [NSString  stringWithFormat:@"%@",[[tempDic  objectForKey:@"data"]  objectForKey:@"content"]];
        CGSize size = [content  calculateSize:CGSizeMake(SCREENWIDTH - 46, 2000) font:[UIFont  systemFontOfSize:12.]];
        return 63 + size.height + picHeight;
    }
    
}

- (UITableViewCell  *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSInteger  row = [indexPath  row];
    NSDictionary  *tempDic = [dataArray  objectAtIndex:row];
    NSInteger  type = [[tempDic  objectForKey:@"type"] integerValue];
    //type: 1老师评语  2作业内容  3我的答案
    if (type == 3) {
        if (editing) {
            static NSString *CellIdentifier = @"StartWriteHomeworkCell";
            StartWriteHomeworkCell  *cell = (StartWriteHomeworkCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"StartWriteHomeworkCell" owner:self options:nil] lastObject];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
                cell.writeDelegate = self;
                cell.textView.text = [NSString  stringWithFormat:@"%@",[[tempDic  objectForKey:@"data"]  objectForKey:@"content"]];
                textView = cell.textView;
            }
            
            [cell  setContentCellWithArray:[[tempDic  objectForKey:@"data"] objectForKey:@"picture"] isEditing:editing];
            
            return cell;
            
        }else {
            static NSString *CellIdentifier = @"HomeWorkContentCell";
            HomeWorkContentCell  *cell = (HomeWorkContentCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
            if (cell == nil) {
                cell = [[[NSBundle mainBundle] loadNibNamed:@"HomeWorkContentCell" owner:self options:nil] lastObject];
                cell.selectionStyle = UITableViewCellSelectionStyleNone;
            }
            
            cell.titleLab.text = @"我的答案";
            cell.detailLab.text = [NSString  stringWithFormat:@"%@",[[tempDic  objectForKey:@"data"]  objectForKey:@"content"]];
            NSMutableArray  *tempArray = [[NSMutableArray  alloc] init];
            NSArray  *picture = [[tempDic  objectForKey:@"data"] objectForKey:@"picture"];
            NSInteger  picCount = [picture  count];
            for (int i = 0; i < picCount; i++) {
                NSDictionary  *tempDic = [picture  objectAtIndex:i];
                if ([[tempDic  objectForKey:@"type"] integerValue] == 1) {
                    [tempArray  addObject:[tempDic  objectForKey:@"data"]];
                }
            }
            [cell  setContentCellWithArray:tempArray];
            
            return cell;
        }
        
    }else {
        static NSString *CellIdentifier = @"HomeWorkContentCell";
        HomeWorkContentCell  *cell = (HomeWorkContentCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
        if (cell == nil) {
            cell = [[[NSBundle mainBundle] loadNibNamed:@"HomeWorkContentCell" owner:self options:nil] lastObject];
            cell.selectionStyle = UITableViewCellSelectionStyleNone;
        }
        
        if (type == 1) {
            cell.titleLab.text = @"老师评语";
        }else if (type == 2) {
            cell.titleLab.text = @"作业内容";
        }else {
            cell.titleLab.text = @"";
        }
        cell.detailLab.text = [NSString  stringWithFormat:@"%@",[[tempDic  objectForKey:@"data"]  objectForKey:@"content"]];
        [cell  setContentCellWithArray:[[tempDic  objectForKey:@"data"] objectForKey:@"picture"]];
        
        return cell;
        
    }
    
}

#pragma mark - UIImagePickerController Delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self  dismissViewControllerAnimated:YES completion:nil];
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    NSData *imageData = UIImageJPEGRepresentation(image, 0.5);
    NSString *tempName = [NSString stringWithFormat:@"%u.jpeg",arc4random()];
    
    [picArray  addObject:[NSDictionary  dictionaryWithObjectsAndKeys:imageData,@"data",@"2",@"type",tempName,@"name", nil]];
    [self.mainTableView  reloadData];
    
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self  dismissViewControllerAnimated:YES completion:nil];
}

#pragma mark - WriteHomeWorkCell Delegate
- (void)deletePictureWithIndex:(NSInteger)index
{
    [picArray  removeObjectAtIndex:index];
    [self.mainTableView  reloadData];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
